﻿using Aurora.AI.Common.Models;

namespace Aurora.AI.Wiki;

/// <summary>
/// 重写SemanticKernel的请求处理
/// </summary>
public sealed class OpenAiHttpClientHandler(AICommonSetting setting) : HttpClientHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        UriBuilder uriBuilder;
        if (!string.IsNullOrWhiteSpace(setting.ChatEndpoint) && request.RequestUri?.LocalPath == "/v1/chat/completions")
        {
            uriBuilder = new UriBuilder(setting.ChatEndpoint.TrimEnd('/') + "/v1/chat/completions");
            request.RequestUri = uriBuilder.Uri;
        }
        else if (!string.IsNullOrWhiteSpace(setting.EmbeddingEndpoint) &&
                 request.RequestUri?.LocalPath == "/v1/embeddings")
        {
            uriBuilder = new UriBuilder(setting.EmbeddingEndpoint.TrimEnd('/') + "/v1/embeddings");
            request.RequestUri = uriBuilder.Uri;
        }
        else if (!string.IsNullOrWhiteSpace(setting.ImagesEndpoint) &&
                request.RequestUri?.LocalPath == "/v1/images/generations")
        {
            uriBuilder = new UriBuilder(setting.ImagesEndpoint.TrimEnd('/') + "/v1/images/generations");
            request.RequestUri = uriBuilder.Uri;
        }

        return await base.SendAsync(request, cancellationToken);
    }
}